using System.Net.Http.Headers;
using System.Text;

namespace Sage.Http.Authentication
{
    /// <summary>
    /// Basic认证提供者
    /// </summary>
    /// <remarks>
    /// 初始化Basic认证提供者
    /// </remarks>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    public class BasicAuthProvider(string username, string password) : IAuthenticationProvider
    {
        private readonly string _username = username ?? throw new ArgumentNullException(nameof(username));
        private readonly string _password = password ?? throw new ArgumentNullException(nameof(password));

        /// <summary>
        /// 获取用户名
        /// </summary>
        public string Username => _username;

        /// <summary>
        /// 获取密码
        /// </summary>
        public string Password => _password;

        /// <summary>
        /// 应用Basic认证
        /// </summary>
        /// <param name="request">HTTP请求</param>
        public Task AuthenticateRequest(HttpRequestMessage request)
        {
            ArgumentNullException.ThrowIfNull(request);

            var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_username}:{_password}"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);

            return Task.CompletedTask;
        }
    }
}
